package com.ruoyi.web.admin.data.command;

import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.system.service.ISysDeviceCollectRecordService;
import com.ruoyi.system.service.ISysDeviceService;
import com.ruoyi.web.admin.data.Constants;
import com.ruoyi.web.admin.data.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 心跳命令处理器
 *
 * @author 10100
 */
@Component
public class HeartBeatCommandHandler implements CommandHandler {


    private static final Logger log = LoggerFactory.getLogger(HeartBeatCommandHandler.class);

    @Resource
    private ISysDeviceService sysDeviceService;

    @Resource
    private ISysDeviceCollectRecordService sysDeviceCollectRecordService;

    @Override
    public String handle(String deviceId, String iccid, String recordId, String command,
                         String type, String timestamp, String length, String body) {
        log.info("设备[{}]心跳请求", deviceId);

        try {
            /*一位当第二位当前步数（每日零点清零）*/
            String batteryLevelStr = body.split("@")[0].replace("%", "");
            SysDevice device = sysDeviceService.selectSysDeviceByeIdentifier(deviceId);
            if (device != null) {
                // 1表示在线
                device.setBatteryLevel(Integer.valueOf(batteryLevelStr));
                device.setConnectionStatus("1");
                device.setLastHeartbeatTime(new Date());
                sysDeviceService.updateSysDevice(device);

                sysDeviceCollectRecordService.insertRecord(device, "POWER", batteryLevelStr, "");
            } else {
                // 设备不存在，创建新设备记录
                log.error("设备[{}]不存在, 心跳请求处理失败", deviceId);
                return null;
            }
        } catch (Exception e) {
            log.error("更新设备[{}]电量时发生错误: {}", deviceId, e.getMessage(), e);
            return null;
        }

        // 构建响应格式
        String responseBody = "0";
        return "[" + deviceId + "," +
                iccid + "," +
                //CommonUtils.generateSerialNumber() + "," +
                CommonUtils.generateSerialNumber() + "," +

                command + "," +
                Constants.REPORT_RESPONSE + "," +
                CommonUtils.getCurrentTimestamp() + "," +
                responseBody.length() + "," +
                responseBody + "]";
    }

    @Override
    public String getCommandType() {
        return "REPORT_HEARTBEAT";
    }
}